/*
 * Copyright (C) 2017 Pingan, Inc. All Rights Reserved.
 */

package com.pingan.haofang.searchcloud.mail.service.impl;

import com.pingan.haofang.searchcloud.mail.dto.MailDto;
import com.pingan.haofang.searchcloud.mail.service.MailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring4.SpringTemplateEngine;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * 邮件发送实现
 *
 * @author zhangbi617
 * @date 2017-10-31
 */
@Service
public class MailServiceImpl implements MailService {

    private static Logger LOG = LoggerFactory.getLogger(MailServiceImpl.class);

    @Autowired(required = false)
    JavaMailSenderImpl javaMailSender;

    @Autowired(required = true)
    MailProperties mailProperties;

    @Autowired
    private SpringTemplateEngine templateEngine;

    @Override
    public void sendMail(MailDto mailDto) {
        LOG.info("\nMail content:\n{}", mailDto.toString());
        try {
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(message);

            String html = render(mailDto.getTemplateName(), mailDto.getModel());
            messageHelper.setText(html, true);
            messageHelper.setFrom(mailProperties.getUsername());
            messageHelper.setTo((String[]) mailDto.getEmailTo().toArray(new String[mailDto.getEmailTo().size()]));
            messageHelper.setSubject(mailDto.getSubject());

            javaMailSender.send(message);
        } catch (MessagingException e) {
            LOG.error("Send mail has a error:{}", e);
        }
    }

    private <T> String render(String template, T model) {
        Context context = new Context(LocaleContextHolder.getLocale());
        context.setVariable("model", model);
        String result = templateEngine.process(template, context);
        return result;
    }
}
